package cn.itsource.service.impl;

import cn.itsource.annotation.Logs;
import cn.itsource.domain.Menu;
import cn.itsource.mapper.MenuMapper;
import cn.itsource.query.MenuQuery;
import cn.itsource.service.IMenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class MenuServiceImpl implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Logs
    @Transactional
    @Override
    @CacheEvict(cacheNames = "menu", key = "'typeTree'")
    public void add(Menu menu) {
        menuMapper.add(menu);
    }
    @Logs
    @Transactional
    @Override
    @CacheEvict(cacheNames = "menu", key = "'typeTree'")
    public void update(Menu menu) {
        menuMapper.update(menu);
    }
    @Logs
    @Transactional
    @Override
    @CacheEvict(cacheNames = "menu", key = "'typeTree'")
    public void del(Long id) {
        menuMapper.del(id);
    }
    @Logs
    @Transactional
    @Override
    @CacheEvict(cacheNames = "menu", key = "'typeTree'")
    public void delList(List<Long> ids) {
        menuMapper.delList(ids);
    }

    @Override
    public Menu get(Long id) {
        return menuMapper.get(id);
    }

    @Override
    public PageInfo<Menu> pageQuery(MenuQuery query) {
        PageHelper.startPage(query.getCurrentPage(),query.getPageSize());
        List<Menu> menus = menuMapper.pageQuery(query);
        redisTemplate.delete("typeTree");
        return new PageInfo<>(menus);
    }

    @Override
    public List<Menu> menyTree() {
       //菜单树
        List<Menu> menuTree = new ArrayList<>();
        //获取所有的文章菜单
        List<Menu> menus = menuMapper.findAll();
        //将所有的菜单装到Map中,方便通过id获取对象
        Map<Long,Menu> map = new HashMap<>();

        for (Menu menu : menus) {
            map.put(menu.getId(),menu);
        }
        //遍历所有的菜单
        for (Menu menu : menus) {
            if(menu.getParentId() == null){//顶级菜单
                menuTree.add(menu);
            }else{//有父菜单
                //获取父id
                Long parentId = menu.getParentId();
                //通过id获取当前对象: 不能调mapper去查
                //1.效率问题 //2.Spring每操作一次数据库时,是新的一个链接
                Menu parentMenu = map.get(parentId);
                if(parentMenu!=null){ //防止parentMenu为空
                    List<Menu> children = parentMenu.getChildren();
                    children.add(menu);
                }
            }
        }
        return menuTree;
    }

}
